<template>
    <div>
        <Toolbar
            class="mb10"
            :programme="programme"
            @advanced="advanced"
            @selectProgramme="selectProgramme"
            @selectMode="selectMode"
        />
        <BaseGrid
            ref="mainGrid"
            show-del-btn
            show-refresh-btn
            show-save
            keep-source
            showFooter
            columnDrop
            :height="height"
            :expand-load-method="expandLoadMethod"
            :columns="config"
            :datas="gridData"
            :loading="loading"
            :show-toolbar-tools="true"
            :show-toolbar-button="true"
            :pagerConfig="pagerConfig"
            :foot="{xszje: 100, wlzt: 200}"
            :rowStyle="rowStyle"
            :showOverflow="showOverflow"
            :treeConfig="false"
            :mergeFooterItems="[
            { row: 0, col: 0, rowspan: 1, colspan: 3 }
            ]"
            @save="save"
            @refresh="refresh"
            @search="search"
            @resizable-change="resizableChange"
            @remove="remove($event,'main')"
            @handlePageChange="(e) => {handlePageChange(e, 'main')}"
            @sortableOnEnd="sortableOnEnd"
        >
            <template #toolbar_button_suf>
                <a-button size="small" @click="showOverflow=!showOverflow">{{showOverflow?'多行':'单行'}}</a-button>
                <a-button size="small" @click="visible=true">冻结前三列</a-button>
            </template>
<!--         <template #header>眼镜</template>-->
<!--         <template #default="{row , column}">-->
<!--                            <a-button-->
<!--                                type="link"-->
<!--                                v-if="column.property === 'pjmx'"-->
<!--                                @click="showAlert(row)"-->
<!--                            >查看</a-button>-->
<!--                        </template>-->
         <template #content="{row}">
                <div class="card-container">
                    <a-tabs
                        class="tabs"
                        type="line"
                        size="small"
                        :tabBarGutter="0"
                        :tabBarStyle="{border:'none'}"
                        @change="change($event, row)"
                    >
                        <a-tab-pane
                            :tab="item.title"
                            v-for="(item,index) in detailConfig.mx"
                            :key="index"
                        ></a-tab-pane>
                    </a-tabs>
                    <div class="flex flex-l">
                        <BaseGrid
                            ref="detailGrid"
                            :columns="detailConfig.columns"
                            :datas="detailGridData"
                            :loading="loadingDetail"
                            padding="0"
                            :more-toolbar="false"
                            @handlePageChange="(e) => {handlePageChange(e, 'detail')}"
                            @remove="remove($event,'detail')"
                            @showAlert="showAlert"
                        >
                            <!--                        <template #default="{row , column}">-->
                            <!--                            <a-button-->
                            <!--                                type="link"-->
                            <!--                                v-if="column.property === 'pjmx'"-->
                            <!--                                @click="showAlert(row)"-->
                            <!--                            >查看</a-button>-->
                            <!--                        </template>-->
                        </BaseGrid>
                    </div>
                </div>

            </template>
        </BaseGrid>
        <BaseAlert
            :loading="loadingSon"
            :show-alert.sync="showAlertModal"
            :columns="sonConfig"
            :datas="sonList"
        />
        <FilterModal ref="iframemodal" :loading="loadingSon" :dd="dd" :advanced.sync="showFilterModal" :config="sonConfig" />
        <vxe-modal v-model="visible">
            <template v-slot>
                <a-button @click="ok">冻结前3列</a-button>
            </template>
        </vxe-modal>
    </div>
</template>

<script>
import BaseGrid from '@/components/base/BaseGrid'
import Toolbar from '@/views/component/component/Toolbar'
import BaseAlert from '@/components/base/BaseAlert'
import FilterModal from './FilterModal'
import XEUtils from 'xe-utils/methods'

// import moment from 'moment'

export default {
    name: 'TableList',
    inheritAttrs: false,
    components: {
        BaseAlert,
        Toolbar,
        BaseGrid,
        FilterModal
    },
    data () {
        return {
            visible: false,
            dd: null,
            loading: false,
            loadingDetail: false,
            loadingSon: false,
            gridData: null,
            config: null,
            detailConfig: null,
            detailGridData: null,
            programme: null,
            selectProgrammeValue: null,
            searchValue: '',
            filter: null,
            pageList: 1,
            showAlertModal: false,
            showFilterModal: false,
            sonConfig: null,
            sonList: null,
            height: document.documentElement.clientHeight - 165,
            modeValue: 0,
            initGetData: false,
            showOverflow: true,
            pagerConfig: {
                total: 100
            }
        }
    },
    props: {
        checkedKeys: {
            type: [Array, Object]
        }
    },
    watch: {
        params: {
            handler (e) {
                console.log('参数：', e)
                if (!this.loading && this.initGetData) {
                    this.getData()
                }
                this.initGetData = true
            },
            immediate: false
        }
    },
    computed: {
        params () {
            return {
                checkedKeys: this.checkedKeys,
                search: this.searchValue,
                programme: this.selectProgrammeValue,
                currentPage: this.pageList,
                filter: this.filter,
                selectModeVal: this.modeValue
            }
        }
    },
    async created () {
        // console.log('moment ', moment('2020/11/12').format('YYYY-MM-DD'))
        const { data } = await this.$api.datacont.getProgramme()
        // // 获取表格配置
        const { data: config } = await this.$api.datacont.getConfig()
        this.config = config.columns
        const { data: detailConfig } = await this.$api.datacont.getDetailConfig()
        this.programme = data.list
        this.detailConfig = detailConfig
        this.getData()
    },
    mounted () {
        window.onresize = () => {
            this.height = `${document.documentElement.clientHeight - 165}`
        }
    },
    methods: {
        ok () {
            this.visible = false
            setTimeout(() => {
                this.toggleFixedColumn(3)
            }, 100)
        },
        // 列拖动回调函数
        sortableOnEnd ({ oldColumnIndex, newColumnIndex, fullColumn }) {
            console.log('变化前位置:', oldColumnIndex)
            console.log('变化后位置:', newColumnIndex)
            console.log('所有列数据:', fullColumn)
        },
        // 列宽发生变化时的回调函数
        resizableChange (e) {
            console.log(e)
        },
        rowStyle ({ row, rowIndex }) {
            if ([2, 3, 5].includes(rowIndex)) {
                return {
                    backgroundColor: '#74cab6',
                    color: '#ffffff'
                }
            }
        },
        save (e) {
            console.log(e)
        },
        // 评估阶段
        // spanMethod ({ _rowIndex, _columnIndex }) {
        //     if (_rowIndex % 2 === 0) {
        //         if (_columnIndex === 4) {
        //             return { rowspan: 1, colspan: 2 }
        //         } else if (_columnIndex === 3) {
        //             return { rowspan: 0, colspan: 0 }
        //         }
        //     }
        // },
        // 表尾合计
        footerMethod ({ columns, data }) {
            const footerData = [
                columns.map((column, _columnIndex) => {
                    if (_columnIndex === 0) {
                        return '平均'
                    }
                    if (['xszje', 'rate'].includes(column.property)) {
                        return XEUtils.mean(data, 'xszje')
                    }
                    // 根据字段名
                    if (['djlczt'].includes(column.property)) {
                        return '展示自定义的值'
                    }
                    // 根据标题
                    if (['#'].includes(column.title)) {
                        return '合并了'
                    }
                    return null
                }),
                columns.map((column, _columnIndex) => {
                    if (_columnIndex === 0) {
                        return '和值'
                    }
                    if (['xszje', 'rate'].includes(column.property)) {
                        return XEUtils.sum(data, 'xszje')
                    }
                    return null
                })
            ]
            return footerData
        },
        // 评估阶段
        footerRowspanMethod ({ _rowIndex, _columnIndex }) {
            if (_rowIndex === 0) {
                if (_columnIndex === 1) {
                    return { rowspan: 2, colspan: 1 }
                }
            } else if (_rowIndex === 1) {
                if (_columnIndex === 1) {
                    return { rowspan: 0, colspan: 0 }
                }
            }
        },
        // 获取接口数据
        async getData () {
            this.loading = true
            setTimeout(async () => {
                const res = this.modeValue === 1 ? await this.$api.datacont.getOneLevelList() : await this.$api.datacont.getList()
                this.gridData = res.data.list
                this.pagerConfig = { ...res.data.page, pageSize: 20 }
                this.loading = false
            }, 400)
        },
        // 分页
        handlePageChange ({ currentPage, pageSize }, type) {
            // if (type === 'main') {
            //   this.pageList = currentPage
            // } else if (type === 'detail') {
            //   this.pageDetail = currentPage
            // }
            // if (type === 'main') {
            //   this.pageList = currentPage
            // } else if (type === 'detail') {
            //   this.pageDetail = currentPage
            // }
            console.log('当前页数+', currentPage)
            this.pageList = currentPage
        },
        // 明细表切换
        change (e, row) {
            console.log(e)
            this.loadingDetail = true
            this.$api.datacont.getDetailList().then(res => {
                row.tabPosition = e
                this.detailGridData = res.data.list
                console.log('this.detailGridData', this.detailGridData)
                this.loadingDetail = false
            })
        },
        // 展开明细
        expandLoadMethod ({ row, rowIndex, $rowIndex }) {
            return new Promise(resolve => {
                return this.$api.datacont.getDetailList().then(res => {
                    console.log('getDetailList', res)
                    const { data } = res
                    this.detailGridData = data.list
                    console.log('getDetailList', data)
                    row.tabPosition = 1
                    resolve()
                })
            })
        },
        // 树节点展开方法
        // treeLoadMethod ({ row }) {
        //     return new Promise(resolve => {
        //         resolve()
        //         // this.$api.datacont.getList().then(res => {
        //         //     resolve(res.data.list)
        //         //     console.log('树节点展开', res.data)
        //         // })
        //     })
        // },
        // 点击查看
        showAlert ({ row, column }) {
            this.sonList = null
            this.showAlertModal = true
            this.loadingSon = true
            setTimeout(async () => {
                const { data: sonConfig } = await this.$api.datacont.getSonConfig()
                const { data } = await this.$api.datacont.getSonList()
                this.sonConfig = sonConfig.columns
                this.sonList = data.list
                console.log('this.sonConfig', this.sonConfig)
                console.log('this.sonList', this.sonList)
                this.loadingSon = false
            }, 500)
        },
        // 高级
        advanced () {
            console.log('高级筛选')
            this.showFilterModal = true
            this.loadingSon = true

            setTimeout(async () => {
                this.loadingSon = false
            }, 500)
        },
        // 刷新
        refresh () {
            this.getData()
            console.log('refresh')
        },
        // 删除
        remove (suc, type) {
            // todo 成功调用删除接口后执行以下删除功能
            if (type === 'main') {
                const ids = []
                var getCheckboxRecords = this.$refs.mainGrid.$refs.xGrid.getCheckboxRecords()
                for (const i in getCheckboxRecords) {
                    ids.push(getCheckboxRecords[i].id)
                }
                var iddata = ids.join(',')
                // 拼接参数
                var params = new FormData()
                params.append('id', iddata)
                this.$api.datacont.delete(params).then(res => {
                    console.log('delete', res)
                    this.$XModal.message({
                        message: '删除成功！',
                        status: 'success'
                    })
                    this.$refs.mainGrid.$refs.xGrid.removeCheckboxRow()
                })
            } else if (type === 'detail') {
                var detailids = []
                var getdetailCheckboxRecords = this.$refs.detailGrid.$refs.xGrid.getCheckboxRecords()
                for (const i in getdetailCheckboxRecords) {
                    detailids.push(getdetailCheckboxRecords[i].id)
                }
                var detailiddata = detailids.join(',')
                // 拼接参数
                var detailparams = new FormData()
                detailparams.append('id', detailiddata)
                this.$api.datacont.delete(detailparams).then(res => {
                    console.log('delete', res)
                    this.$XModal.message({
                        message: '删除成功！',
                        status: 'success'
                    })
                    this.$refs.detailGrid.$refs.xGrid.removeCheckboxRow()
                })
            }
        },
        // 搜索
        search (e) {
            this.searchValue = e
            console.log('搜索内容：', e)
        },
        // 方案选择
        selectProgramme ({ value }) {
            this.selectProgrammeValue = value
            console.log('方案选择：', value)
        },
        // 切换模式
        selectMode ({ value }) {
            console.log('模式选择：', value)
            // 获取表格配置
            setTimeout(async () => {
                // 获取表格配置
                const { data: config } = this.modeValue === 1 ? await this.$api.datacont.getOneLevelConfig() : await this.$api.datacont.getConfig()
                this.config = config.columns
            }, 400)
            this.modeValue = value
        },
        // 冻结第二/第三列 注：列下标从0开始
        toggleFixedColumn (columns = 3) {
            const column = [...Array(columns).keys()]
            this.$refs.mainGrid.toggleFixedColumn(column, 'left')
        }
    }
}
</script>

<style scoped lang="less">
.card-container {
    //background: #f5f5f5;
    overflow: hidden;
    position: relative;
    /deep/ .ant-tabs-bar {
        margin: 0;
        //background: #11c1f3;
        //position: absolute;
        //top: 10px;
        //left: 10px;
        //z-index: 2;
    }
    .tabs{
        background: #ffbd17;
        position: absolute;
        left: 0;
        top: 8px;
        z-index: 2;
        width: auto!important;
        display: block;
    }
}
</style>
